<template>
  <!-- 这是购物车页面 -->
  <div class="star">
    <div>
      <h2>购物车</h2>
      <el-divider></el-divider>
    </div>
    <el-table
      :data="
        tableData.filter(
          (data) =>
            !search || data.fname.toLowerCase().includes(search.toLowerCase())
        )
      "
      style="width: 100%"
      highlight-current-row
      show-header
      @selection-change="handleSelectionChange"
      :row-key = "rowkey"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>

      <el-table-column label="ID" prop="gwcId"> </el-table-column>
      <el-table-column label="鲜花名称" prop="fname"> </el-table-column>

      <el-table-column label="图片" width="80">
        <template slot-scope="scope">
          <!-- {{scope.row.url}} -->
          <img
            :src="require(`../../assets/${scope.row.url}`)"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column label="花语" prop="descs"> </el-table-column>
      <el-table-column label="价格">
        <template slot-scope="scope">
          ￥{{scope.row.price}}
        </template>
      </el-table-column>
      <el-table-column label="数量">
        <template slot-scope="scope">
          <div style="" :class="{ counting: true, disabled }">
            <div class="reduce" @click="changNum2('-', scope.row.gwcId, scope.$index)">
              -
            </div>
            <div class="input_box">
              <div class="wrap" v-if="disabled" />
              <input
                  type="text"
                  v-model="scope.row.cnt"
                  @blur="changNum2('input', scope.row.gwcId, scope.$index)"
                  @keyup="amountKeydownFun(scope.row.gwcId, scope.$index)"
              />
            </div>
            <div class="add" @click="changNum2('+', scope.row.gwcId, scope.$index)">
              +
            </div>
          </div>
        </template>

      </el-table-column>
      <el-table-column align="right">
        <template slot="header">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入鲜花名称搜索您想要的东西"
          />
        </template>
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="compute">
      <div class="heji">
        已选<span class="price"> {{ number }}</span> 件，合计：<span
          class="price"
          >{{ sum }}</span
        >
      </div>
      <div class="jiesuan">
        <el-button type="primary" round icon="el-icon-goods" size="small"
          @click="goBuy">结算</el-button
        >
      </div>
    </div>

    <div class="footer">
      <div class="elbutton">
        <el-button type="danger" plain size="small" @click="deleteMore"
          >批量删除</el-button
        >
      </div>

      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

  <script>
export default {
  components: {},
  name: "counting",
  props: {
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      numObj: {
        num: 1,
        type: ""
      },
      tableData: [],
      search: "",
      radio: "",
      number: 0,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection:[],
      userInfo: localStorage.getItem("user")
        ? JSON.parse(localStorage.getItem("user"))
        : {},

    };
  },
  watch: {

  },
  computed: {
    // 计算合计
    sum:function(){
      var i = 0
      this.multipleSelection.forEach((item) =>{
        i += item.price*item.cnt;
      });
      return i
    }
  },
  methods: {
    amountKeydownFun(id, index) {
      if (this.tableData[(this.currentPage-1)*this.pageSize + index].cnt.length == 1) {
        this.tableData[(this.currentPage-1)*this.pageSize + index].cnt = this.tableData[(this.currentPage-1)*this.pageSize + index].cnt.toString().replace(/[^1-9]/g, 1);
      } else {
        this.tableData[(this.currentPage-1)*this.pageSize + index].cnt = this.tableData[(this.currentPage-1)*this.pageSize + index].cnt.toString().replace(/\D/g, 1);
      }
      this.updateCnt(id, this.tableData[(this.currentPage-1)*this.pageSize + index].cnt, this.tableData[(this.currentPage-1)*this.pageSize + index].fid);
    },
    changNum2(type, id, index) {
      if (this.disabled) return;
      // 点击加号或者减号
      if (type == "+" || type == "-") {
        // +
        if (type == "+") {
          this.tableData[(this.currentPage-1)*this.pageSize + index].cnt++;
        }
        // -
        if (type == "-") {
          this.tableData[(this.currentPage-1)*this.pageSize + index].cnt--;
          if (this.tableData[(this.currentPage-1)*this.pageSize + index].cnt < 1) {
            this.tableData[(this.currentPage-1)*this.pageSize + index].cnt = 1;
          }
        }
      }
      // 输入框输入
      if (type == "input") {
        if (this.tableData[(this.currentPage-1)*this.pageSize + index].cnt.toString().indexOf(".") != -1) {
          let idx = this.tableData[(this.currentPage-1)*this.pageSize + index].cnt.toString().indexOf(".");
          this.tableData[(this.currentPage-1)*this.pageSize + index].cnt = Number(this.tableData[(this.currentPage-1)*this.pageSize + index].cnt.toString().slice(0, idx));
        }
        if (this.tableData[(this.currentPage-1)*this.pageSize + index].cnt <= 1 || this.tableData[(this.currentPage-1)*this.pageSize + index].cnt === '') {

          this.tableData[(this.currentPage-1)*this.pageSize + index].cnt = 1
        }
      }
      this.updateCnt(id, this.tableData[(this.currentPage-1)*this.pageSize + index].cnt,  this.tableData[(this.currentPage-1)*this.pageSize + index].fid);

    },
    // 删除
    handleDelete(index, row) {
      this.$confirm("小主！您的操作将在购物车删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.request.delete("/gwc/" + row.gwcId).then((res) => {
            if (res.data.code === "200") {
              this.$message.success("已听从您的指示！为您净化空间啦！");
              this.load();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "还好还好！可以挽回！已为您取消删除该商品",
          });
        });
    },
    updateCnt(id, cnt, fid) {
      this.request.get("/gwc/updateCnt?gwcId=" + id + '&cnt=' +cnt + '&fid=' + fid).then((res) => {
        if (res.data.code === "200") {
          this.load();
        } else {
          this.$message.error("操作失败!");
          this.load();
        }
      });
    },
    // 批量删除
    deleteMore() {
      let ids = this.multipleSelection.map((v) => v.gwcId);

      this.$confirm(
        "小主！您的操作将在您的购物车里批量删除这些鲜花, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          this.request.post("/gwc/del/batch", ids).then((res) => {
            if (res.data.code === "200") {
              this.$message.success("已听从您的指示！为您净化空间啦！");
              this.load();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "还好还好！可以挽回！已为您取消删除这些好看的鲜花！",
          });
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.number = val.length
    },
  // 结算
    goBuy() {
    if (this.multipleSelection.length === 0) {
      this.$message({
        type: "warning",
        message: "请选择商品！",
      });
    } else {
      // 进入结算页面之前把选中的数据存到state里
      this.$store.state.select = this.multipleSelection;
      this.$store.state.time = '';
      this.$router.push("/buy");
    }
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },

    // 页面初始化
    load() {
      this.request
        .get("/gwc/page", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            uid: this.userInfo.data.id,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    rowkey(row){
      return row.gwcId
    }
  },
  created() {
    if (this.userInfo.data === undefined) {
      this.$router.push("/login");
      this.$message({
        showClose: true,
        type: "warning",
        message: "请进行登录！",
      });
    }
    this.load();
  },
  mounted() {},
};
</script>
<style lang="less" scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
.star {
  .compute {
    float: right;
    display: flex;
    // margin-bottom: 5%;
    // position: fixed; 是相对于浏览器窗口固定的。即使窗口滚动。他也不会移动
    position: fixed;
    top: 650px;
    right: 45px;

    .heji {
      // float: right;
      margin: 13px 50px;
      text-align: center;
      .price {
        color: red;
        font-size: 20px;
      }
    }
    .jiesuan {
      margin: 10px;
    }
  }
  .footer {
    display: flex;
    justify-content: space-between;
    .elbutton {
      padding-top: 15px;
    }
    .block {
      float: right;
      margin-top: 15px;
    }
  }
}


.counting {
  width: 92px;
  height: 24px;
  border: 1px solid #EBEDF0;
  border-radius: 2px;
  user-select: none;
  display: inline-block;
  &.disabled{
    border: 1px solid #F7F8F9;
    .reduce {
      border-right: 1px solid #F7F8F9;
      color: #ADADAE;
    }
    .input_box {
      color: #ADADAE;
      input {
        color: #ADADAE;
      }
    }
    .add {
      border-left: 1px solid #F7F8F9;
      color: #ADADAE;
    }
  }
  div {
    float: left;
    box-sizing: border-box;
    text-align: center;
    line-height: 24px;
    height: 24px;
  }
  .reduce {
    width: 24px;
    border-right: 1px solid #EBEDF0;
    font-size: 14px;
    color: #444;
    text-align: center;
    font-weight: 400;
    cursor: pointer;
  }
  .input_box {
    width: calc(100% - 24px - 24px);
    position: relative;
    .wrap {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(255, 255, 255, 0.4);
    }
    input {
      border: 0;
      width: 100%;
      height: 100%;
      line-height: 24px;
      font-size: 14px;
      color: #323233;
      text-align: center;
      font-weight: 400;
      /*添加css样式*/
      &::-webkit-outer-spin-button,
      &::-webkit-inner-spin-button {
        -webkit-appearance: none;
      }
      &[type="number"] {
        -moz-appearance: textfield;
      }
    }
  }
  .add {
    width: 24px;
    border-left: 1px solid #EBEDF0;
    font-size: 14px;
    color: #444;
    text-align: center;
    font-weight: 400;
    cursor: pointer;
  }
  .add,.reduce {
    position: relative;
    &:hover {
      .tip {
        display: block;
      }
    }
    .tip {
      display: none;
      position: absolute;
      height: auto;
      top: 33px;
      left: 50%;
      transform: translateX(-50%);
      -webkit-transform: translateX(-50%);
      background: #303133;
      color: #FFF;
      padding: 3px 10px;
      font-size: 12px;
      border-radius: 4px;
      white-space: nowrap;
      z-index: 91;
      .triangle {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        top: -15px;
        width: 0;
        height: 0;
        border: 8px solid #303133;
        border-right: 8px solid rgba(255, 255, 255, 0);
        border-left: 8px solid rgba(255, 255, 255, 0);
        border-top: 8px solid rgba(255, 255, 255, 0);
      }
    }
  }
}
</style>